var bcrypt = dcodeIO.bcrypt;

function signup() {
    const name = document.getElementById('newname').value;
    const email = document.getElementById('newemail').value;
    const password1 = document.getElementById('newpassword1').value;
    const password2 = document.getElementById('newpassword2').value;
    const termsChecked = document.getElementById('terms').checked; 

     if (!termsChecked) {
        const choice = confirm('You must agree to the terms and conditions to register.');
        if (!choice) {
            return; 
        }
    }
    if (password1 === password2) {
        // create a random salt value
        // encrypt the password with the salt
        const salt = bcrypt.genSaltSync(10);
        const hashedPassword = bcrypt.hashSync(password1, salt);
        users = JSON.parse(localStorage.getItem("users"));
    if (users === null) //if there are no users yet
        users = []; //initialize it to empty
        const existingUser = users.find(u => u.email === email);
        if (existingUser) {
            alert("A user with this email already exists.");
            return;
        }
        const weight = 0;
        const location = 'China';
        const food = 'potato';
        users.push({ 
            name, 
            email, 
            password: hashedPassword, 
            weight,
            location,
            food
        });

        alert('User registered with hashed password. Welcome ' + name);

        localStorage.setItem("users", JSON.stringify(users));
        window.location.href = "./Userlogin.html";
        } else {
        alert('Passwords do not match!');
    }
}

function login() {
    // read the "database" of users from local storage
    users = JSON.parse(localStorage.getItem("users"));
    // read the login email and password
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    
    const user = users.find(u => u.email === email);

    if (user && bcrypt.compareSync(password, user.password)) {
        alert('Login successful! for ' + user.name);
        localStorage.setItem("loggedinUser", JSON.stringify(user));
        window.location.href = "./recipes.html";
        } else {
        alert('Login failed.');
        }
}
